package io.http;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import utils.Md5Tools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * HTTP操作类，所有从HTTP读取数据，写入数据均在本类中完成
 * Created by jcala on 2016/3/14.
 */
public class HTTPHandler {
    //Url为手机验证码平台API地址
    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    /**
     * 从HttpServletRequest中读取json数据为字符串
     * @param request Servlet中的HttpServletRequest
     * @return 读取到的json数据字符串
     */
    public static String receiveFromHTTP(HttpServletRequest request) {
        BufferedReader br = null;
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 发送json数据字符串到Servlet的HttpServletResponse中
     * @param response Servlet中的HttpServletResponse
     * @param jsonString 要写入到HTTP中的json数据
     */
    public static void sendMsgToHTTP(HttpServletResponse response,String jsonString){
        PrintWriter writer=null;
        try {
            writer=response.getWriter();
            writer.write(jsonString);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(writer!=null){
                writer.close();
            }
        }

    }

    /**
     * 暂未使用：打算从HttpServletRequest获取ip，再通过IP获取客户端的物理位置，再进行天气查询和PM2.5等信息查询
     *从Servlet中的HttpServletRequest读取到客户端IP
     * @param request Servlet中的HttpServletRequest
     * @return IP地址
     */
    public static String getIp(HttpServletRequest request){
        String ip=request.getHeader("x-forwarded-for");
        if(ip==null||ip.length()<=0||"unknown".equalsIgnoreCase(ip)){
           ip=request.getHeader("Proxy-Client-IP");
        }
        if(ip==null||ip.length()<=0||"unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("WL-Proxy-Client-Ip");
        }
        if(ip==null||ip.length()<=0||"unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("HTTP_CLIENT_IP");
        }
        if(ip==null||ip.length()<=0||"unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if(ip==null||ip.length()<=0||"unknown".equalsIgnoreCase(ip)){
            ip=request.getRemoteAddr();
        }
        return ip;
    }

    /**
     *根据城市名称，通过一个API接口获取包含城市信息的字符串
     * @param cityName 城市的中文名
     * @return
     */
    public static String sendGet(String cityName) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "http://api.lib360.net/open/pm2.5.json?city=" + cityName;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                    result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 注意：在此处NameValuePair中需要自己加入互亿无线平台用户名和密码
     * 向API发送POST请求，以让用户获取验证码
     * @param number 要发送到的手机号
     * @param mobile_code 要发送给手机的随机验证码
     * @return 包含操作状态信息的字符串
     */
    public static String setMsg(String number,int mobile_code){
        String result=null;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "username"),
                new NameValuePair("password", Md5Tools.MD5Encode("password")),
                new NameValuePair("mobile", "手机号码"),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            result=method.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
